<template>
	<div class="tableTemplateSecondClass">
		<vxe-table ref="vxeTableSecondRef" keep-source @current-change="currentChange" :loading="tableDataLoading"
			show-overflow border size="mini" :column-config="{ resizable: true }" :row-config="{ useKey: true, keyField: 'id', isCurrent: true, isHover: true }"
			:edit-config="{ trigger: 'click', mode: 'cell' }"
			:tree-config="{ transform: true, rowField: 'id', parentField: 'parentId', expandAll: true }" :data="tableData"
			:scroll-y="{ enabled: false }">
			<vxe-column field="field" title="参数名称" width="200" tree-node header-align="center">
				<template #default="{ row }">
					<template v-if="row.parentId != 0">
						<span v-if="row.parentId == -1">+</span>
						<el-select :style="[{ width: (row.parentId == -1 ? '96%' : '100%') }]" v-model="row.field"
							placeholder="请选择">
							<el-option @click.native="changeQueryOptions(item, row, $event)"
								v-for="(item, index) in queryOptions.filter(opt => opt && opt.field != null)" :key="index"
								:label="!!item.title ? item.title : item.field"
								:value="item.field || ''">
							</el-option>
						</el-select>
					</template>
					<template v-else>
						<span>条件组</span>
					</template>
				</template>
			</vxe-column>
			<vxe-column field="comparator" title="比较符" width="150" header-align="center">
				<template #default="{ row }">
					<template v-if="row.parentId != 0">
						<el-select v-model="row.comparator" placeholder="请选择">
							<el-option v-for="(item, index) in comparatorOptions" :key="index" :label="item.label"
								:value="item.value">
							</el-option>
						</el-select>
					</template>
				</template>
			</vxe-column>
			<vxe-column field="value" title="比较值" header-align="center">
				<template #default="{ row }">
					<template v-if="row.parentId != 0">
						<template v-if="row.controlType == 'select'">
							<!-- <el-select style="width: 100%;" v-model="row.value" placeholder="请选择">
								<el-option label="比较值1" value="&&" />
								<el-option label="比较值2" value="||" />
							</el-select> -->
						</template>
						<template v-else-if="row.controlType == 'date'">
							<el-date-picker :field="row.field" type="date" style="width: 100%;" v-model="row.value" placeholder="请选择"
								value-format="yyyy-MM-dd" />
						</template>
						<template v-else-if="row.controlType == 'datetime'">
							<el-date-picker :field="row.field" type="datetime" style="width: 100%;" v-model="row.value" placeholder="请选择"
								value-format="yyyy-MM-dd HH:mm:ss" />
						</template> 
						<template v-else-if="row.controlType == 'daterange'">
							<el-date-picker :field="row.field" type="daterange" style="width: 100%;" v-model="row.value" placeholder="请选择"
								value-format="yyyy-MM-dd" />
						</template>
						<template v-else-if="row.controlType == 'datetimerange'">
							<el-date-picker :field="row.field" type="datetimerange" style="width: 100%;" v-model="row.value" placeholder="请选择"
								value-format="yyyy-MM-dd HH:mm:ss" />
						</template>
						<!-- 下拉框 -->
						<template v-else-if="row.controlType == 'reportSelect'">
							<reportSelect :field="row.field" v-model="row.value" style="width: 100%;" :row="row"></reportSelect>
						</template>
						<!-- 下拉框(表) -->
						<template v-else-if="row.controlType == 'reportSelectTable'">
							<reportSelectTable :field="row.field" :fieldName="row.field" v-model="row.value" style="width: 100%;" :row="row">
							</reportSelectTable>
						</template>
						<!-- 下拉框(自定义) -->
						<template v-else-if="row.controlType == 'customSelect'">
							<reportCustomSelect :field="row.field" v-model="row.value" style="width: 100%;" :row="row"></reportCustomSelect>
						</template>
							<!-- 下拉框(自定义多选) -->
						 <template v-else-if="row.controlType == 'customMulSelect'">
							<reportCustomMulSelect :field="row.field" v-model="row.value" style="width: 100%;" :row="row"></reportCustomMulSelect>
						</template>
						<!-- 下拉框(多选) -->
						<template v-else-if="row.controlType == 'reportMulSelect'">
							<reportMulSelect :field="row.field" v-model="row.value" style="width: 100%;" :row="row"></reportMulSelect>
						</template>
						<template v-else-if="row.controlType == 'number'">
							<el-input-number :field="row.field" style="width: 100%;" v-model="row.value"></el-input-number>
						</template>
						<template v-else>
							<el-input :field="row.field" v-model="row.value" placeholder="请输入" />
						</template>
					</template>
				</template>
			</vxe-column>
			<vxe-column field="relationSign" title="关系" width="70" header-align="center">
				<template #default="{ row }">
					<!-- <template v-if="row.parentId != 0">
						
					</template> -->
					<el-select v-model="row.relationSign" placeholder="请选择">
						<el-option label="并" :value="0" />
						<el-option label="或" :value="1" />
						<el-option label="无" :value="-1" />
					</el-select>
				</template>
			</vxe-column>
			<vxe-column title="操作" width="80" header-align="center" align="center" show-overflow>
				<template #default="{ row }">
					<vxe-button v-show="(!isSystemDefaultSolution || !solutionCID)" style="color:red;" mode="text"
						icon="vxe-icon-delete" @click="removeRow(row)">删除</vxe-button>
				</template>
			</vxe-column>
		</vxe-table>
	</div>
</template>
<script setup>
import VXETable from 'vxe-table'
import { ref, reactive, watch, nextTick, getCurrentInstance } from 'vue'
// import { useRoute } from 'vue-router'
import axios from "@/libs/request.js";
import reportSelect from '../innerComponents/reportSelect.vue'
import reportCustomMulSelect from '../innerComponents/reportCustomMulSelect.vue'
import reportCustomSelect from '../innerComponents/reportCustomSelect.vue'
import reportSelectTable from '../innerComponents/reportSelectTable.vue'
import reportMulSelect from '../innerComponents/reportMulSelect.vue'

const sqlServeSearchType = [
	{ value: 0, label: '等于', text: 'Equal' },
	{ value: 1, label: '模糊查询', text: 'Like' },
	{ value: 2, label: '大于', text: 'GreaterThan' },
	{ value: 3, label: '大于等于', text: 'GreaterThanOrEqual' },
	{ value: 4, label: '小于', text: 'LessThan' },
	{ value: 5, label: '小于等于', text: 'LessThanOrEqual' },
	{ value: 6, label: 'In操作', text: 'In' },
	{ value: 7, label: 'NotIn操作', text: 'NotIn' },
	{ value: 8, label: '左模糊', text: 'LikeLeft' },
	{ value: 9, label: '右模糊', text: 'LikeRight' },
	{ value: 10, label: '不等于', text: 'NoEqual' },
	{ value: 11, label: 'IsNullOrEmpty', text: 'IsNullOrEmpty' },
	{ value: 12, label: 'IsNot', text: 'IsNot' },
	{ value: 13, label: '模糊查询取反', text: 'NoLike' },
	{ value: 14, label: 'EqualNull ', text: 'EqualNull' },
	{ value: 15, label: 'InLike', text: 'InLike' },
	{value:16,label:'区间范围 ',text:'BetweenAnd'},
]

// Props
const props = defineProps({
	// 清空发生改变
	isClearTreeData: {
		type: [String, Number],
		default: ""
	},
	// 当前选中的解决方案
	solutionCID: {
		type: [String, Number],
		default: ""
	},
	// 方案列表
	solutionList: {
		type: Array,
		default: () => []
	},
	// 子系统传递过来的值对象
	optionModel: {
		type: Object,
		default() {
			return {}
		}
	},
	// 表单信息
	formSolution: {
		type: Object,
		default() {
			return {}
		}
	},
	conditionConfig: {
		type: Object,
		default() {
			return {
				hash: 698,
				flag: ''//条件组:group 条件:condition
			}
		}
	}
})

// Emits
const emit = defineEmits(['formDataChangeFn', 'disabledDeleteBtnFn', 'submitSuccess', 'submitBtnLoadingFn'])

// Composables
// const route = useRoute()
let fullURL = window.location.href;
const instance = getCurrentInstance()

// Reactive data
const loadDataConfig = ref(null)
const isSystemDefaultSolution = ref(false) // 是否系统默认解决方案
const tableDataLoading = ref(false)
const editResDataObj = ref(null) // 编辑时，对象
const submitBtnLoading = ref(false)
const removeBtnLoading = ref(false)
const currentSelectedRow = ref(null)
const currentSelectedItem = ref(null)
const comparatorOptions = ref(sqlServeSearchType)
const queryOptions = ref([])
const tableData = ref([])

// Refs
const vxeTableSecondRef = ref(null)
// Watchers
watch(() => props.isClearTreeData, (n, o) => {
	if (n) {
		resetData()
	}
}, { deep: true, immediate: false })

watch(() => props.conditionConfig, (val, old) => {
	// debugger
	nextTick(() => {
		addConditionFn(val)
		if (queryOptions.value && queryOptions.value.length == 0) {
			getSystemSolutions()
		}
	})
}, { deep: true, immediate: false })

// Methods
// 清空发生回调事件
const resetData = () => {
	currentSelectedRow.value = null
	currentSelectedItem.value = null
	// 清空表格数据
	tableData.value = []
	// 重置其他相关状态
	props.solutionCID =""
	loadDataConfig.value = null
	queryOptions.value = []
	setTimeout(() => {
		const $table = vxeTableSecondRef.value
		if ($table) {
			$table.reloadData([])
		}
	}, 300)
}
// 当前行字段发生改变，同时也改变了当前字段的控件类型
const changeQueryOptions = (item, row, $event) => {
	row.controlType = item.controlType
	row.title = item.title
	row.isCheck = true// new
	row.tableName = item.tableName
	row.controlOptions = item.controlOptions
}
const submitBtnLoadingFn = (val) => {
	emit("submitBtnLoadingFn", val)
}
const getRequest = (name) => {
	let urlStr = window.location.search
	let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	let r = urlStr.substr(1).match(reg);
	if (r != null) {
		return unescape(r[2]);
	};
	return null;
}

// 批量设置设置默认为 非默认值
const EditBatch = async () => {
	let _url = `/api/system/Common/EditBatch`
	if (!props.solutionCID || !props.optionModel.searchProSettingCPARENT) {
		return
	}
	let params = {
		"ConnId": "",
		"table": "TBL_SYS_ADVANCED_SEARCH", // 固定参数
		"ModelJson": "{\"CDEFAULT\":false}",
		"where": "CPARENT=" + `'${props.optionModel.searchProSettingCPARENT}' AND CID <> ${props.solutionCID}`
	}
	await axios.request({
		url: _url,
		method: "post",
		data: params,
	}).then(res => {
		if (!!res.Success) {
			// 成功处理
		}
	})
}
const submitEditDialog = async () => {
	// 如果表格数据为空，则不提交
	const $table = vxeTableSecondRef.value
	let visibleData =[]
	if ($table) {
		visibleData = $table.getTableData().visibleData //处理条件之后的全量表体数据
	}
	if (visibleData.length <= 0) {
		// 提示错误信息
		VXETable.modal.message({message:'数据不能为空', status:'error' })
		return
	}
	submitBtnLoadingFn(true)
	let _url = `/api/SYSTEM/Common/Insert`

	let formName = getRequest("formName") // 页面ID
	if(!!!formName){
		// 如果为空，说明非单页面数据，需要使用路由名称作为唯一页面ID
		formName = window.location.pathname //route.path
	}
	let modelJson = {}
	//debugger
	// 如果当前方案ID 不为空，即可编辑状态
	if (!!props.solutionCID) {
		_url = `/api/system/Common/Edit`
		modelJson = Object.assign({}, editResDataObj.value)
	}
	modelJson.CPID = formName // 页面ID
	modelJson.CSCHEME_NAME = props.formSolution.name//方案名称
	modelJson.CVISIBILITY_USER_ID = props.formSolution.region//可见性(用户ID) NULL或o表示所有人,反之为用户Id
	modelJson.CCONDITION = getConditionTableDataJSON()//查询条件 json
	modelJson.CTEMPLATE_ID = !!props.solutionCID ? props.solutionCID : "" //方案ID
	modelJson.CGROUP = props.optionModel.searchProSettingCPARENT // 组,已经无效注释了，改为 CPARENT
	modelJson.CPARENT = props.optionModel.searchProSettingCPARENT // 组
	modelJson.CDEFAULT = props.formSolution.defaultOption // 是否默认
	delete modelJson.RowIndex // 移除多余的字段
	let params = {
		"table": "TBL_SYS_ADVANCED_SEARCH", // 固定参数
		modelJson: JSON.stringify(modelJson)
	}

	await axios.request({
		url: _url,
		method: "post",
		data: params,
	}).then(res => {
		if (!!res.Success) {
			submitBtnLoadingFn(false)
			// 使用 ElMessage 替代 this.$message
			// ElMessage({
			// 	message: !!res.Content ? res.Content : '执行成功',
			// 	type: 'success'
			// });
			resetData()
			setTimeout(() => {
				emit("submitSuccess", {})
			}, 300)
			// 如果是编辑 并且设置了当前选中的方案为默认 查询方案
			if (!!props.solutionCID && !!modelJson.CDEFAULT) {
				// 批量设置其它相同模板为非默认 查询方案
				EditBatch()
			}
		}
	})
}
const getConditionTableDataJSON = () => {
	let _tablefullData = []
	const $table = vxeTableSecondRef.value
	if ($table) {
		_tablefullData = $table.getTableData().visibleData //处理条件之后的全量表体数据
	}
	//debugger
	// 将 树状结构数据 转为 扁平数据
	_tablefullData = removeTreeChildren(_tablefullData)
	//debugger
	let CCONDITION = {
		tableData: _tablefullData,
		loadDataConfig: loadDataConfig.value,
		// 方便扩展其它字段
	}
	return JSON.stringify(CCONDITION)
}

// 将 移除 树状结构数据 下的children节点数据
const removeTreeChildren = (treeData = []) => {
	let newTreeData = []
	treeData.forEach(item => {
		delete item.children
		newTreeData.push(item)
	})
	return newTreeData
}

// 将 树状结构数据 转为 扁平数据
const toFlat = (treeData = []) => {
	return treeData.reduce((result, node) => {
		if (node.children) {
			result.push(...toFlat(node.children));
			// 如果有节点 添加前先移除
			delete node.children
		}
		result.push(node);
		return result;
	}, []);
}
const currentChange = (tableInfo) => {
	if (tableInfo.row.parentId == 0) {
		currentSelectedRow.value = tableInfo.row
	} else {
		currentSelectedRow.value = null
	}
	currentSelectedItem.value = tableInfo.row
}

const addConditionFn = (val) => {
	//条件组:group 条件:condition
	let type = val.flag
	switch (type) {
		// 条件组:
		case "group":
			addGroupClick()
			break;
		// 条件
		case "condition":
			addConditionClick()
			break;
		default:
			break;
	}
}

// 添加条件
const addConditionClick = async () => {
	//debugger
	if (!!currentSelectedRow.value) {
		await insertRow(currentSelectedRow.value, 'bottom')
	} else {
		addCommonRow()
	}
}
const addCommonRow = async () => {
	let randomparentId = Math.floor(Math.random() * 1000000 + 1)
	let randomID = randomparentId
	let record = {
		id: randomID,
		parentId: -1,
		field: '',
		title: '',
		check: null,
		isCheck: true,
		controlType: 'text',
		defaultValue: '',
		tableName: '',
		comparator: 0,
		relationSign: 0,
		value: '',
	}
	const $table = vxeTableSecondRef.value
	//debugger
	if (currentSelectedItem.value && currentSelectedItem.value.parentId == -1) {
		const { row: newRow } = await $table.insertAt(record, currentSelectedItem.value)
		$table.setCurrentRow(newRow) // 插入子节点
	} else {
		const { row: newRow } = await $table.insertAt(record, -1)
		$table.setCurrentRow(newRow) // 插入子节点
	}
}

// 添加条件组
const addGroupClick = async () => {
	let randomparentId = Math.floor(Math.random() * 1000000 + 1)
	let randomID = randomparentId
	let record = {
		id: randomID,
		parentId: 0,
		field: '',
		title: '',
		isCheck: true,
		controlType: 'text',
		defaultValue: '',
		tableName: '',
		comparator: 0,
		relationSign: 0,
		value: '',
	}
	const $table = vxeTableSecondRef.value
	// insertAt 如果 -1 则插入到目标节点底部
	const { row: newRow } = await $table.insertAt(record, -1)
	$table.setCurrentRow(newRow) // 插入子节点
	currentSelectedRow.value = newRow
	currentSelectedItem.value = newRow
}
// 删除高级查询配置信息
const removeConditionClick = () => {
	// 使用 ElMessageBox 替代 this.$confirm
	// ElMessageBox.confirm('此操作将删除高级查询配置数据, 是否继续?', '提示', {
	// 	confirmButtonText: '确定',
	// 	cancelButtonText: '取消',
	// 	type: 'warning'
	// }).then(() => {
	// 	deleteData()
	// }).catch(() => {
	// 	// 取消操作
	// });
}

const deleteData = async () => {
	removeBtnLoading.value = true
	let _url = `/api/SYSTEM/Common/Remove`

	let params = {
		"table": "TBL_SYS_ADVANCED_SEARCH", // 固定参数
		CID: props.optionModel.searchProSettingID // 页面ID
	}

	await axios.request({
		url: _url,
		method: "post",
		data: params,
	}).then(res => {
		if (!!res.Success) {
			removeBtnLoading.value = false
			// resetData()
			// 使用 ElMessage 替代 this.$message
			// ElMessage({
			// 	message: !!res.Content ? res.Content : '执行成功',
			// 	type: 'success'
			// });
			setTimeout(() => {
				// 关闭高级搜索配置弹框
				// showEditDialogFlag.value = false
			}, 300)
		}
	})
}
const removeRow = async (row) => {
	const $table = vxeTableSecondRef.value
	await $table.remove(row)
	try {
		if (currentSelectedRow.value && currentSelectedRow.value.parentId && currentSelectedRow.value.parentId == row.parentId && row.parentId == 0) {
			currentSelectedRow.value = null
		}
		if (currentSelectedItem.value && currentSelectedItem.value.id == row.id) {
			currentSelectedItem.value = null
		}
	} catch (error) {
		// 错误处理
	}
}

const insertRow = async (currRow, locat) => {
	let randomID = (Math.floor(Math.random() * 1000000 + 1))
	const $table = vxeTableSecondRef.value
	// 如果 null 则插入到目标节点顶部
	// 如果 -1 则插入到目标节点底部
	// 如果 row 则有插入到效的目标节点该行的位置
	if (locat === 'current') {
		const record = {
			id: randomID,
			parentId: currRow.parentId,
			field: '',
			title: '',
			isCheck: true,
			controlType: 'text',
			defaultValue: '',
			tableName: '',
			comparator: 0,
			relationSign: 0,
			value: '',
		}
		const { row: newRow } = await $table.insertAt(record, currRow)
		await $table.setCurrentRow(newRow) // 插入子节点
		currentSelectedItem.value = newRow
	} else if (locat === 'top') {
		const record = {
			id: randomID,
			parentId: currRow.id,
			field: '',
			title: '',
			isCheck: true,
			controlType: 'text',
			defaultValue: '',
			tableName: '',
			comparator: 0,
			relationSign: 0,
			value: '',
		}
		const { row: newRow } = await $table.insert(record)
		await $table.setTreeExpand(currRow, true) // 将父节点展开
		await $table.setCurrentRow(newRow) // 插入子节点
		currentSelectedItem.value = newRow
	} else if (locat === 'bottom') {
		const record = {
			id: randomID,
			parentId: currRow.id,
			field: '',
			title: '',
			isCheck: true,
			controlType: 'text',
			defaultValue: '',
			tableName: '',
			comparator: 0,
			relationSign: 0,
			value: '',
		}
		const { row: newRow } = await $table.insertAt(record, -1)
		await $table.setTreeExpand(currRow, true) // 将父节点展开
		await $table.setCurrentRow(newRow) // 插入子节点
		currentSelectedItem.value = newRow
	}
}
// 加载数据并清除所有状态（对于表格数据需要重载、局部更新被修改的数据）
const reloadData = (dataList) => {
	const $table = vxeTableSecondRef.value
	if ($table) {
		$table.reloadData(dataList)
	}
}

// 方案ID 切换 改变
const solutionCID_change = (val_CID) => {
	//debugger
	if (queryOptions.value && queryOptions.value.length == 0) {
		getSystemSolutions()
	}
	tableDataLoading.value = true
	let defaultData = filterSolutionByCID(val_CID)
	if (defaultData) {
		let CCONDITION = JSON.parse(defaultData.CCONDITION)
		// 查询条件
		if (CCONDITION.tableData) {
			tableData.value = CCONDITION.tableData
		}
		// 查询控件配置参数
		if (CCONDITION.loadDataConfig) {
			loadDataConfig.value = CCONDITION.loadDataConfig
		}

		editResDataObj.value = defaultData
		// 表单内容发生改变
		emit("formDataChangeFn", defaultData)
	}

	setTimeout(() => {
		tableDataLoading.value = false
		setAllTreeExpand()
	}, 100)
}

// 用于 tree-config，设置所有树节点的展开与否
const setAllTreeExpand = () => {
	const $table = vxeTableSecondRef.value
	if ($table) {
		$table.setAllTreeExpand(true)
	}
}

// 从解决方案列表通过CID 过滤获取
const filterSolutionByCID = (CID) => {
	//debugger
	isSystemDefaultSolution.value = false
	if (CID == props.optionModel.searchProSettingID) {
		isSystemDefaultSolution.value = true
	}
	emit("disabledDeleteBtnFn", isSystemDefaultSolution.value)
	let defaultItem = null
	// 如果没有设置默认值，则取系统添加的解决方案
	let filterListBy_CID = props.solutionList.filter(item => {
		if (item.CID == CID) {
			return item
		}
	})
	if (filterListBy_CID && filterListBy_CID.length > 0) {
		defaultItem = filterListBy_CID[0]
	}
	return defaultItem
}

// 获取系统配置的默认查询方案
const getSystemSolutions = () => {
	debugger
	queryOptions.value = []
	let defaultSystemSolution = filterSolutionByCID(props.optionModel.searchProSettingID)
	if (defaultSystemSolution) {
		let CCONDITION = JSON.parse(defaultSystemSolution.CCONDITION)
		if (CCONDITION.tableData) {
			let _dataList = CCONDITION.tableData
			queryOptions.value = _dataList.filter(item => {
				if (!!item.field) {
					return item
				}
			})
		}
	}
}



// 暴露给父组件的方法
defineExpose({
	reloadData,
	solutionCID_change,
	submitEditDialog
})
</script>
<style lang="scss" scoped>
/* 样式设定 自动适应 表格高度 */
.tableTemplateClass {
	margin-right: 10px;
	/*  
	:deep(.vxe-table--body-wrapper) {
		height: calc(100vh - 180px); 
	}*/ 
}

.tableTemplateSecondClass {
	margin-right: 10px;
	/* 
	:deep(.vxe-table--body-wrapper)  {
		height: calc(100vh - 280px); 
	}*/  
}

</style>